import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { loginApi } from "@/api/index";
import { useMenuStore } from "./menu";
import { getToken, setToken, removeToken } from "@/utils/auth";
// 定义用户信息接口
export interface UserInfo {
  username: string | null;
  name: string | null;
  phone: string | null;
  avatar: string | null;
  description: string | null;
  role: string | null;
  isAuthenticated: boolean;
}

export const useUserStore = defineStore("user", () => {
  // 获取菜单store
  const menuStore = useMenuStore();
  
  // 定义状态
  const user = ref<UserInfo>({
    username: null,
    name: null,
    phone: null,
    avatar: null,
    description: null,
    role: null,
    isAuthenticated: false,
  });
  const token = ref<string | null>(getToken());

  //用户登录
  const login = async (params: any) => {
    const { userName, password, captcha, codeKey } = params;
    return new Promise((resolve, reject) => {
      loginApi({ userName: userName.trim(), password, captcha, codeKey })
        .then((response) => {
          // 登录成功，更新用户信息和token
          const { data } = response;
          token.value = data.token;
          setToken(data.token);
          
          // 登录成功，更新用户信息
          if (data.userInfo) {
            setUserInfo({
              username: data.userName || data.userInfo.username,
              name: data.userInfo.name,
              phone: data.userInfo.phone,
              avatar: data.userInfo.avatar,
              description: data.userInfo.description,
              role: data.userInfo.role,
            });
          }
          

          
          // 登录成功后获取最新的菜单数据
          menuStore.getAllMenus();
          
          resolve(true);
        })
        .catch((error) => {
          reject(error);
        });
    });
  };

  // 由于不需要权限检查，此方法总是返回true
  const hasPermission = (permission: string) => {
    return true;
  };

  // 定义 actions
  // 设置用户信息
  function setUserInfo(userInfo: Partial<UserInfo>) {
    Object.assign(user.value, userInfo);
    user.value.isAuthenticated = true;

    // 将用户信息保存到localStorage
    saveUserInfoToStorage();
  }

  // 清除用户信息（登出）
  function clearUserInfo() {
    user.value = {
      username: null,
      name: null,
      phone: null,
      avatar: null,
      description: null,
      role: null,
      isAuthenticated: false,
    };
    token.value = null;

    // 从localStorage移除用户信息
    localStorage.removeItem("userInfo");
    removeToken();
    
    // 清除菜单
    menuStore.clearMenus();
  }

  // 从localStorage加载用户信息
  function loadUserInfoFromStorage() {
    const storedUserInfo = localStorage.getItem("userInfo");
    if (storedUserInfo) {
      try {
        const userInfo = JSON.parse(storedUserInfo);
        Object.assign(user.value, userInfo);
        user.value.isAuthenticated = !!getToken();
      } catch (error) {
        console.error("Failed to load user info from localStorage:", error);
      }
    }
  }

  // 更新用户头像
  function updateAvatar(avatarUrl: string) {
    user.value.avatar = avatarUrl;
    // 更新localStorage中的用户信息
    saveUserInfoToStorage();
  }

  // 保存用户信息到localStorage
  function saveUserInfoToStorage() {
    const { username, name, phone, avatar, description, role } = user.value;
    localStorage.setItem(
      "userInfo",
      JSON.stringify({
        username,
        name,
        phone,
        avatar,
        description,
        role,
      })
    );
  }

  return {
    user,
    token,
    login,
    hasPermission,
    setUserInfo,
    clearUserInfo,
    loadUserInfoFromStorage,
    updateAvatar,
    saveUserInfoToStorage,
  };
});
